package easy.trace.plugin.mybatis;

import easy.trace.common.Span;
import easy.trace.core.context.SqlTraceContext;
import easy.trace.core.context.TraceContext;

import easy.trace.core.dto.MySQLEvent;
import easy.trace.core.dto.TransferParams;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Invocation;

/**
 * @author easy
 */
public class MybatisContext implements SqlTraceContext {
    private MappedStatement mappedStatement;
    private Invocation invocation;
    private static final String EVENT_TYPE_MYBATIS = "MYBATIS";


    public MybatisContext(Invocation invocation) {
        this.invocation = invocation;
        this.mappedStatement = (MappedStatement) invocation.getArgs()[0];
    }

    @Override
    public MySQLEvent getMySQLEvent(){
        return MybatisContextParser.showSqlEvent(this.invocation.getArgs(), (MappedStatement) this.invocation.getArgs()[0]);
    }

    /**
     * 得到类名
     *
     * @return
     */
    @Override
    public String getServiceId() {
        return MybatisContextParser.getServiceMapper(mappedStatement);
    }

    /**
     * 得到方法名称
     *
     * @return
     */
    @Override
    public String getMethod() {
        return MybatisContextParser.getMethodMapper(mappedStatement);
    }

    @Override
    public String getEventType() {
        return EVENT_TYPE_MYBATIS;
    }

    @Override
    public boolean isCaller() {
        return true;
    }

    @Override
    public boolean isCalled() {
        return false;
    }

    @Override
    public int port() {
        return 0;
    }

    @Override
    public String address() {
        return null;
    }

    @Override
    public TransferParams getTransferParams() {
        return null;
    }

    @Override
    public void setTransferParams(Span span) {
      /*  Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String eventData = MybatisContextParser.getEventData(parameter, mappedStatement);
        span.setEventData(JSON.toJSONString(eventData));*/
    }
}
